package com.campus.client.view;

import com.campus.client.controller.TeacherAccountManagementController;
import com.campus.client.net.ClientConnector;
import com.campus.common.vo.Teacher;
import com.campus.common.vo.User;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Callback;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class TeacherAccountManagementFrame {
    private TeacherAccountManagementController teacherController;
    private TableView<Teacher> teacherTable;
    private MenuBar menuBar;
    private Button backBtn;
    private Button processRequestsBtn;

    private User user=new User();
    public User getUser() {return user;}
    public void setUser(String Id,String password,String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
        //System.out.print("用户名"+this.user.getId());
    }

    public void start(Stage primaryStage) throws Exception {
        teacherController = new TeacherAccountManagementController(new ClientConnector("172.20.10.2", 8888));

        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.getStyleClass().add("main-container");

        // 顶部标题栏
        HBox headerBox = new HBox();
        headerBox.getStyleClass().add("header-box");
        headerBox.setAlignment(Pos.CENTER_LEFT);
        headerBox.setPadding(new Insets(10, 15, 10, 15));

        Label titleLabel = new Label("教师账号管理 - 管理员版");
        titleLabel.getStyleClass().add("header-title");

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        // 创建菜单栏
        menuBar = createMenuBar();

        Region buttonSpacer = new Region();
        buttonSpacer.setPrefWidth(10);

        backBtn = createStyledButton("返回");
        backBtn.getStyleClass().add("secondary-button");
        backBtn.setOnAction(e -> back());

        headerBox.getChildren().addAll(titleLabel, spacer, menuBar, buttonSpacer, backBtn);
        root.setTop(headerBox);

        // 内容区域
        VBox contentBox = new VBox();
        contentBox.getStyleClass().add("content-box");
        contentBox.setPadding(new Insets(15));

        // 添加搜索面板
        HBox searchPanel = createSearchPanel();
        contentBox.getChildren().add(searchPanel);

        // 创建表格
        teacherTable = new TableView<>();
        teacherTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        setupTableColumns();

        // 添加表格到滚动面板
        ScrollPane scrollPane = new ScrollPane(teacherTable);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        scrollPane.getStyleClass().add("scroll-pane");

        contentBox.getChildren().add(scrollPane);
        root.setCenter(contentBox);

        // 添加底部按钮区域
        HBox bottomBox = new HBox();
        bottomBox.setAlignment(Pos.BOTTOM_RIGHT);
        bottomBox.setPadding(new Insets(10, 0, 10, 0));

        processRequestsBtn = createStyledButton("处理请求");
        processRequestsBtn.getStyleClass().add("primary-button");
        processRequestsBtn.setOnAction(e -> {
            try {
                showTeacherApprovalFrame();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });

        bottomBox.getChildren().add(processRequestsBtn);
        root.setBottom(bottomBox);

        // 默认加载所有教师
        loadAllTeachers();

        Scene scene = new Scene(root, 1200, 700);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        primaryStage.setTitle("教师账号管理 - 管理员版");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // 创建菜单栏
    private MenuBar createMenuBar() {
        MenuBar menuBar = new MenuBar();
        menuBar.getStyleClass().add("teacher-menu-bar");

        Menu viewMenu = new Menu("显示操作");
        MenuItem allTeachersItem = new MenuItem("显示所有教师");
        allTeachersItem.setOnAction(e -> loadAllTeachers());

        Menu manageMenu = new Menu("管理");
        MenuItem addTeacherItem = new MenuItem("新增教师");
        addTeacherItem.setOnAction(e -> showAddTeacherDialog());

        viewMenu.getItems().add(allTeachersItem);
        manageMenu.getItems().add(addTeacherItem);

        menuBar.getMenus().addAll(viewMenu, manageMenu);
        return menuBar;
    }

    // 创建搜索面板
    private HBox createSearchPanel() {
        HBox searchPanel = new HBox(10);
        searchPanel.setPadding(new Insets(10));
        searchPanel.setAlignment(Pos.CENTER_LEFT);

        TextField searchField = new TextField();
        searchField.setPromptText("输入姓名或工号");
        searchField.setPrefWidth(200);

        Button searchButton = createStyledButton("搜索");
        searchButton.setOnAction(e -> {
            String keyword = searchField.getText().trim();
            if (!keyword.isEmpty()) {
                try {
                    List<Teacher> teachersByName = teacherController.searchTeachersByName(keyword);
                    List<Teacher> teachersById = teacherController.searchTeachersById(keyword);

                    // 合并结果，去重
                    List<Teacher> resultList = new ArrayList<>();
                    resultList.addAll(teachersByName);
                    resultList.addAll(teachersById);

                    // 去重
                    for (int i = 0; i < resultList.size(); i++) {
                        for (int j = i + 1; j < resultList.size(); j++) {
                            if (resultList.get(i).getTeacherId().equals(resultList.get(j).getTeacherId())) {
                                resultList.remove(j);
                                j--;
                            }
                        }
                    }

                    displaySearchResults(resultList, keyword);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    showAlert("错误", "搜索失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                }
            }
        });

        Button clearButton = createStyledButton("清除搜索");
        clearButton.setOnAction(e -> {
            searchField.clear();
            loadAllTeachers();
        });

        searchPanel.getChildren().addAll(
                new Label("搜索:"), searchField, searchButton, clearButton
        );

        return searchPanel;
    }

    // 设置表格列
    private void setupTableColumns() {
        // 工号列
        TableColumn<Teacher, String> idCol = new TableColumn<>("工号");
        idCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getTeacherId()));
        idCol.setMinWidth(100);

        // 姓名列
        TableColumn<Teacher, String> nameCol = new TableColumn<>("姓名");
        nameCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getName()));
        nameCol.setMinWidth(80);

        // 年龄列
        TableColumn<Teacher, String> ageCol = new TableColumn<>("年龄");
        ageCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                String.valueOf(cellData.getValue().getAge())));
        ageCol.setMinWidth(60);

        // 性别列
        TableColumn<Teacher, String> sexCol = new TableColumn<>("性别");
        sexCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                cellData.getValue().getSex()));
        sexCol.setMinWidth(60);

        // 部门列
        TableColumn<Teacher, String> departmentCol = new TableColumn<>("部门");
        departmentCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                cellData.getValue().getDepartment()));
        departmentCol.setMinWidth(120);

        // 联系方式列
        TableColumn<Teacher, String> contactCol = new TableColumn<>("联系方式");
        contactCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(
                cellData.getValue().getContactInfo()));
        contactCol.setMinWidth(120);

        // 操作列
        TableColumn<Teacher, Void> actionCol = new TableColumn<>("操作");
        actionCol.setMinWidth(200);
        actionCol.setCellFactory(new Callback<TableColumn<Teacher, Void>, TableCell<Teacher, Void>>() {
            @Override
            public TableCell<Teacher, Void> call(final TableColumn<Teacher, Void> param) {
                return new TableCell<Teacher, Void>() {
                    private final Button deleteBtn = createStyledButton("删除");
                    private final Button updateBtn = createStyledButton("修改");
                    private final HBox pane = new HBox(10, deleteBtn, updateBtn);

                    {
                        pane.setAlignment(Pos.CENTER);
                        deleteBtn.getStyleClass().add("danger-button");
                        updateBtn.getStyleClass().add("primary-button");

                        deleteBtn.setOnAction(event -> {
                            Teacher teacher = getTableView().getItems().get(getIndex());
                            Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
                            confirmAlert.setTitle("确认删除");
                            confirmAlert.setHeaderText("确定要删除教师 " + teacher.getName() + " 吗？");
                            confirmAlert.setContentText("此操作不可恢复。");

                            confirmAlert.showAndWait().ifPresent(response -> {
                                if (response == ButtonType.OK) {
                                    try {
                                        Boolean success = teacherController.deleteTeacher(teacher.getTeacherId());
                                        if (success) {
                                            showAlert("成功", "删除教师成功", Alert.AlertType.INFORMATION);
                                            loadAllTeachers();
                                        } else {
                                            showAlert("失败", "删除教师失败", Alert.AlertType.ERROR);
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        showAlert("错误", "删除失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                                    }
                                }
                            });
                        });

                        updateBtn.setOnAction(event -> {
                            Teacher teacher = getTableView().getItems().get(getIndex());
                            showUpdateDialog(teacher);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(pane);
                        }
                    }
                };
            }
        });

        teacherTable.getColumns().addAll(idCol, nameCol, ageCol, sexCol, departmentCol, contactCol, actionCol);
    }

    // 加载所有教师
    private void loadAllTeachers() {
        try {
            List<Teacher> teachers = teacherController.getTeachers();
            teacherTable.getItems().setAll(teachers);
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载教师数据失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // 显示搜索结果
    private void displaySearchResults(List<Teacher> teachers, String keyword) {
        teacherTable.getItems().setAll(teachers);
    }

    // 显示新增教师对话框
    private void showAddTeacherDialog() {
        Dialog<Teacher> dialog = new Dialog<>();
        dialog.setTitle("新增教师");
        dialog.setHeaderText("请输入教师信息");

        // 设置按钮
        ButtonType addButtonType = new ButtonType("添加", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(addButtonType, ButtonType.CANCEL);

        // 创建表单
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField nameField = new TextField();
        nameField.setPromptText("姓名");

        TextField teacherIdField = new TextField();
        teacherIdField.setPromptText("工号");

        Spinner<Integer> ageSpinner = new Spinner<>(1, 100, 30);

        ComboBox<String> sexComboBox = new ComboBox<>();
        sexComboBox.getItems().addAll("男", "女");
        sexComboBox.setValue("男");

        TextField departmentField = new TextField();
        departmentField.setPromptText("部门");

        TextField contactField = new TextField();
        contactField.setPromptText("联系方式");

        grid.add(new Label("姓名:"), 0, 0);
        grid.add(nameField, 1, 0);
        grid.add(new Label("工号:"), 0, 1);
        grid.add(teacherIdField, 1, 1);
        grid.add(new Label("年龄:"), 0, 2);
        grid.add(ageSpinner, 1, 2);
        grid.add(new Label("性别:"), 0, 3);
        grid.add(sexComboBox, 1, 3);
        grid.add(new Label("部门:"), 0, 4);
        grid.add(departmentField, 1, 4);
        grid.add(new Label("联系方式:"), 0, 5);
        grid.add(contactField, 1, 5);

        dialog.getDialogPane().setContent(grid);

        // 转换结果为Teacher对象
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == addButtonType) {
                Teacher newTeacher = new Teacher();
                newTeacher.setName(nameField.getText().trim());
                newTeacher.setTeacherId(teacherIdField.getText().trim());
                newTeacher.setAge(ageSpinner.getValue());
                newTeacher.setSex(sexComboBox.getValue());
                newTeacher.setDepartment(departmentField.getText().trim());
                newTeacher.setContactInfo(contactField.getText().trim());
                return newTeacher;
            }
            return null;
        });

        Optional<Teacher> result = dialog.showAndWait();
        result.ifPresent(teacher -> {
            try {
                boolean success = teacherController.addTeacher(teacher);
                if(success){
                    showAlert("添加成功", "新增教师信息成功", Alert.AlertType.INFORMATION);
                    loadAllTeachers();
                }
                else{
                    showAlert("添加失败", "新增教师信息成功", Alert.AlertType.ERROR);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "添加失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });
    }

    // 显示更新教师对话框
    private void showUpdateDialog(Teacher teacher) {
        Dialog<Teacher> dialog = new Dialog<>();
        dialog.setTitle("更新教师信息");
        dialog.setHeaderText("更新教师信息");

        // 设置按钮
        ButtonType updateButtonType = new ButtonType("更新", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(updateButtonType, ButtonType.CANCEL);

        // 创建表单
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField nameField = new TextField(teacher.getName());
        TextField teacherIdField = new TextField(teacher.getTeacherId());
        teacherIdField.setEditable(false); // 工号不可编辑

        Spinner<Integer> ageSpinner = new Spinner<>(1, 100, teacher.getAge());

        ComboBox<String> sexComboBox = new ComboBox<>();
        sexComboBox.getItems().addAll("男", "女");
        sexComboBox.setValue(teacher.getSex());

        TextField departmentField = new TextField(teacher.getDepartment());
        TextField contactField = new TextField(teacher.getContactInfo());

        grid.add(new Label("姓名:"), 0, 0);
        grid.add(nameField, 1, 0);
        grid.add(new Label("工号:"), 0, 1);
        grid.add(teacherIdField, 1, 1);
        grid.add(new Label("年龄:"), 0, 2);
        grid.add(ageSpinner, 1, 2);
        grid.add(new Label("性别:"), 0, 3);
        grid.add(sexComboBox, 1, 3);
        grid.add(new Label("部门:"), 0, 4);
        grid.add(departmentField, 1, 4);
        grid.add(new Label("联系方式:"), 0, 5);
        grid.add(contactField, 1, 5);

        dialog.getDialogPane().setContent(grid);

        // 转换结果为Teacher对象
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == updateButtonType) {
                teacher.setName(nameField.getText().trim());
                teacher.setAge(ageSpinner.getValue());
                teacher.setSex(sexComboBox.getValue());
                teacher.setDepartment(departmentField.getText().trim());
                teacher.setContactInfo(contactField.getText().trim());
                return teacher;
            }
            return null;
        });

        Optional<Teacher> result = dialog.showAndWait();
        result.ifPresent(updatedTeacher -> {
            try {
                boolean success = teacherController.updateTeacher(updatedTeacher);
                if (success) {
                    showAlert("成功", "更新教师信息成功", Alert.AlertType.INFORMATION);
                    loadAllTeachers(); // 刷新列表
                } else {
                    showAlert("失败", "更新教师信息失败", Alert.AlertType.ERROR);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "更新失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });
    }

    // 统一按钮创建方法
    private Button createStyledButton(String text) {
        Button button = new Button(text);
        button.getStyleClass().add("styled-button");
        return button;
    }

    // 统一提示对话框
    private void showAlert(String title, String message, Alert.AlertType type) {
        Alert alert = new Alert(type, message, ButtonType.OK);
        alert.setHeaderText(title);
        alert.showAndWait();
    }

    private void back() {
        // 获取当前窗口的Stage
        Stage currentStage = (Stage) backBtn.getScene().getWindow();
        currentStage.close();

        // 这里可以添加返回主界面的逻辑
        // 例如：打开管理员主界面
        try {
            AccountManagementFrame accountManagementFrame = new AccountManagementFrame();
            accountManagementFrame.setUser(user.getId(), user.getPassword(), user.getRole());
            accountManagementFrame.start(new Stage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showTeacherApprovalFrame() throws Exception {
        // 获取当前登录窗口的Stage
        Stage registerStage = (Stage) processRequestsBtn.getScene().getWindow();

        // 创建主界面
        TeacherApprovalFrame teacherApprovalFrame = new TeacherApprovalFrame();
        teacherApprovalFrame.setUser(user.getId(), user.getPassword(),  user.getRole());
        Stage teacherApprovalStage = new Stage();

        // 显示主界面
        teacherApprovalFrame.start(teacherApprovalStage);

        // 关闭登录窗口
        registerStage.close();
    }
}